import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_single_choice_button_widget/common_single_choice_button_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';

import 'bean/company_choose_terminal_response_bean.dart';
import 'company_choose_terminal_list_view_model.dart';
import 'widgets/company_choose_terminal_list_item_widget.dart';

/// 企业选择终端
///
/// @author: zengxiangxi
/// @createTime: 1/8/21 10:07 AM
/// @specialDemand:
class CompanyChooseTerminalListPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "CompanyChooseTerminalListPage";

  final List<CompanyChooseTerminalListItemBean> selectedList;

  const CompanyChooseTerminalListPage({Key key, this.selectedList})
      : super(key: key);

  @override
  _CompanyChooseTerminalListPageState createState() =>
      _CompanyChooseTerminalListPageState();

  ///跳转方法
  static Future<List<CompanyChooseTerminalListItemBean>> navigatorPush(
      BuildContext context,
      List<CompanyChooseTerminalListItemBean> selectedList) {
    return RouterUtils.routeForFutureResult<
        List<CompanyChooseTerminalListItemBean>>(
      context,
      CompanyChooseTerminalListPage(selectedList: selectedList),
      routeName: CompanyChooseTerminalListPage.ROUTER,
    );
  }
}

class _CompanyChooseTerminalListPageState extends BasePagerState<
    CompanyChooseTerminalListItemBean,
    CompanyChooseTerminalListPage> with VgPlaceHolderStatusMixin {
  CompanyChooseTerminalListViewModel _viewModel;

  List<CompanyChooseTerminalListItemBean> newSelectList;
  @override
  void initState() {
    super.initState();
    newSelectList = List<CompanyChooseTerminalListItemBean>();
    _viewModel = CompanyChooseTerminalListViewModel(this, () {
      return "";
    }, widget?.selectedList);
    _viewModel?.refresh();
    if((widget?.selectedList?.length??0)!=0){
      // newSelectList = widget?.selectedList;
      newSelectList.addAll(widget?.selectedList);
    }
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
       Scaffold(
        backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        body: _toMainColumnWidget(),
      ),
      navigationBarColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        Container(
          padding: EdgeInsets.symmetric(vertical: 10),
          color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          child: CommonSearchBarWidget(
            hintText: "搜索",
            onChanged: (String str){
              _viewModel = CompanyChooseTerminalListViewModel(this, () {
                return str;
              }, newSelectList);
              _viewModel?.refresh();
              setState(() { });
            },
          ),
        ),
        Expanded(
          child: MixinPlaceHolderStatusWidget(
              errorOnClick: () => _viewModel?.refresh(),
              emptyOnClick: () => _viewModel?.refresh(),
              child: _toPullRefreshWidget()),
        )
      ],
    );
  }

  Widget _toPullRefreshWidget() {
    return VgPullRefreshWidget.bind(
        state: this,
        viewModel: _viewModel,
        enablePullDown: false,
        child: ListView.separated(
            itemCount: data?.length ?? 0,
            padding: const EdgeInsets.all(0),
            physics: BouncingScrollPhysics(),
            keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
            itemBuilder: (BuildContext context, int index) {
              return CompanyChooseTerminalListItemWidget(
                itemBean: data?.elementAt(index),
                onTap: (CompanyChooseTerminalListItemBean itemBean) {
                  if (itemBean == null) {
                    return;
                  }
                  if(itemBean.selectStatus == CommonSingleChoiceStatus.unSelect){
                    itemBean.selectStatus = CommonSingleChoiceStatus.selected;
                    if((newSelectList?.length??0) !=0){
                      List<String> hsns = [];
                      newSelectList?.forEach((element) {
                        hsns?.add(element?.hsn);
                      });
                      if(!(hsns?.toString()?.contains(itemBean?.hsn))){
                        newSelectList?.add(itemBean);
                      }
                    }else{
                      newSelectList?.add(itemBean);
                    }
                  }else if(itemBean.selectStatus == CommonSingleChoiceStatus.selected){
                    itemBean.selectStatus = CommonSingleChoiceStatus.unSelect;
                    newSelectList?.remove(itemBean);
                  }
                  setState(() { });
               },
              );
            },
            separatorBuilder: (BuildContext context, int index) {
              return SizedBox(
                height: 0,
              );
            }));
  }

  ///topbar
  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      title: "管理终端",
      isShowBack: true,
      rightWidget: CommonFixedHeightConfirmButtonWidget(
        isAlive: !(isEmptyStatus || isErrorStatus || isLoadingStatus),
        width: 48,
        height: 24,
        unSelectBgColor:
            ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
        selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 12,
            fontWeight: FontWeight.w600),
        selectedTextStyle: TextStyle(
            color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
        text: "确定",
        onTap: () {
          _toPopSelectedList();
        }
      ),
    );
  }

  @override
  void setListData(List<CompanyChooseTerminalListItemBean> list) {
    super.setListData(list);
    newSelectList.clear();
    newSelectList.addAll(list);
  }

  void _toPopSelectedList() {
    if((isEmptyStatus || isErrorStatus || isLoadingStatus)){
      VgToastUtils.toast(context, "数据加载中～");
      return ;
    }
    if(newSelectList == null || newSelectList.isEmpty){
      if(newSelectList == null){
        newSelectList = List();
      }
      RouterUtils.pop(context, result: newSelectList);
      return;
    }
    List<CompanyChooseTerminalListItemBean> resultList = List();
    for(CompanyChooseTerminalListItemBean item in newSelectList){
      if(item.selectStatus == CommonSingleChoiceStatus.selected){
        resultList?.add(item);
      }
    }
    RouterUtils.pop(context,result: resultList);
  }
}
